package com.gree.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SessionFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) arg0;
		HttpServletResponse httpResponse = (HttpServletResponse) arg1;
		String loginUrl = httpRequest.getContextPath() + "/Views/index.jsp";
		String url = httpRequest.getRequestURI();
		if (!url.contains("index") && httpRequest.getSession(false) == null) {// index是我的登录页的路径
			//	String str = "<script language='javascript'>alert('会话过期,请重新登录');"+ "window.top.location.href='" + loginUrl + "';</script>";
			String str = "<script language='javascript'>window.top.location.href='" + loginUrl + "';</script>";
			httpResponse.setContentType("text/html;charset=UTF-8");// 解决中文乱码
			PrintWriter writer = httpResponse.getWriter();
			writer.write(str);
			writer.flush();
			return;
		}
		chain.doFilter(httpRequest, httpResponse);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {}

}
